﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SchoolLibrary.Entity;

namespace SchoolLibrary.DataBase.DAO
{
    public class ClassDAO : AbstractDAO<Class>
    {
        private static ClassDAO instance;

        private ClassDAO() { }

        public static ClassDAO getInstance()
        {
            if (instance == null)
            {
                instance = new ClassDAO();
            }
            return instance;
        }

        public override Class findById(long id)
        {
            Query classQuery = new Query(Class.FIND_BY_ID);
            classQuery.setParameter("id", id);
            return getDAOHelper().getSingleResult(classQuery);
        }

        public override List<Class> findAll()
        {
            Query classQuery = new Query(Class.FIND_ALL);
            return getDAOHelper().getResultList(classQuery);
        }

        public override void save(Class pupilClass)
        {
            if (pupilClass.Id != UNDIFINED_ID)
            {
                save(pupilClass, Class.UPDATE);
            }
            else
            {
                save(pupilClass, Class.SAVE);
            }
        }

        private void save(Class pupilClass, string queryString)
        {
            Query query = new Query(queryString);
            query.setParameter("id", pupilClass.Id);
            query.setParameter("number", pupilClass.Number);
            query.setParameter("letter", pupilClass.Letter);
            query.setParameter("classLeaderId", pupilClass.ClassLeader.Id);
            getDAOHelper().executeUpdate(query);
        } 
    }
}
